
const base64ToUtf8 = (base64String : string) => {
    const binaryString = atob(base64String);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    const utf8String = new TextDecoder('utf-8').decode(bytes);
    return utf8String;
}

export const loadResources = (topicId : string) => {
    const url = `https://haijiao.com/api/topic/${topicId}`
    return new Promise((resolve, reject) => {
        fetch(url, { mode: 'cors' })
            .then(response => response.json())
            .then(async data => {
                // 在这里处理返回的数据
                if (!data.success) {
                    console.log(data)
                    return
                }
                data.isEncrypted && (data.data = JSON.parse(atob(atob(atob(data.data)))))
                console.log(data.data)
                const props = data.data.attachments.map(async (item: any) => {
                                        if (item.category !== "video") return item
                                        return await loadVideoSrc(item.id, topicId)
                                    })
                const attachments = await Promise.all(props)
                // console.log(attachments)
                resolve({ attachments })
            })
    })
}
export const parseTopic = (topicId : string) => {
    const url = `https://haijiao.com/api/topic/${topicId}`
    return new Promise((resolve, reject) => {
        get(url, null).then(async (data: any)=> {
            const props = data.attachments.map(async (item: any) => {
                                    if (item.category !== "video") return item
                                    return await loadVideoSrc(item.id, topicId)
                                })
            const attachments = await Promise.all(props).catch(error=>{
                console.log(error)
                resolve(data)
            })
            if(attachments) {
                data.attachments = attachments
                resolve(data)
            }
        }).catch(err=>{
            console.log(err)
            reject(err)
        })
    })
}

const  loadVideoSrc = async (id: string, resource_id: string) => {
    return new Promise(async (resolve, reject) => {
        const {user} = await browser.storage.local.get("user")
        const data = {
            "id": parseInt(id),
            "resource_id": parseInt(resource_id),
            "resource_type": "topic",
            "line": ""
        }
        // 定义自定义的请求头信息
        const myHeaders = new Headers();
        myHeaders.append('X-User-Id', user?.uid);
        myHeaders.append('X-User-Token', user?.token);
        myHeaders.append('Content-Type', 'application/json');
        fetch(`https://haijiao.com/api/attachment`, {
            method: 'POST',
            headers: myHeaders,
            body: JSON.stringify(data), 
            "mode": "cors",
            "credentials": "include",
            "referrer": "https://haijiao.com/post/details?pid=1734971",
            "referrerPolicy": "strict-origin-when-cross-origin",
        }).then( resp => resp.json())
        .then(async data => {
            // 在这里处理返回的数据
            if (!data.success) {
                console.log(data)
                reject(data.message)
                return
            }
            data.isEncrypted && (data.data = JSON.parse(atob(atob(atob(data.data)))))
            resolve(data.data)
        })

    })
}


export const loadImg = (items) => {
    function w() {
        var e = "ABCD*EFGHIJKLMNOPQRSTUVWX#YZabcdefghijklmnopqrstuvwxyz1234567890"
            , t = (this.encode = function (i) {
                var a, n, o, r, s, c, l = "", u = 0;
                for (i = t(i); u < i.length;)
                    o = (a = i.charCodeAt(u++)) >> 2,
                        r = (3 & a) << 4 | (a = i.charCodeAt(u++)) >> 4,
                        s = (15 & a) << 2 | (n = i.charCodeAt(u++)) >> 6,
                        c = 63 & n,
                        isNaN(a) ? s = c = 64 : isNaN(n) && (c = 64),
                        l = l + e.charAt(o) + e.charAt(r) + e.charAt(s) + e.charAt(c);
                return l;
            }, this.decode = function (t) {
                var a, n, o, r, s, c, l = "", u = 0;
                for (t = t.replace(/[^A-Za-z0-9\*\#]/g, ""); u < t.length;)
                    o = e.indexOf(t.charAt(u++)),
                        a = (15 & (r = e.indexOf(t.charAt(u++)))) << 4 | (s = e.indexOf(t.charAt(u++))) >> 2,
                        n = (3 & s) << 6 | (c = e.indexOf(t.charAt(u++))),
                        l += String.fromCharCode(o << 2 | r >> 4),
                        64 != s && (l += String.fromCharCode(a)),
                        64 != c && (l += String.fromCharCode(n));
                return i(l)
            }, function (e) {
                e = e.replace(/\r\n/g, "\n");
                for (var t = "", i = 0; i < e.length; i++) {
                    var a = e.charCodeAt(i);
                    a < 128 ? t += String.fromCharCode(a) : t = 127 < a && a < 2048 ? (t += String.fromCharCode(a >> 6 | 192)) + String.fromCharCode(63 & a | 128) : (t = (t += String.fromCharCode(a >> 12 | 224)) + String.fromCharCode(a >> 6 & 63 | 128)) + String.fromCharCode(63 & a | 128)
                }
                return t
            }), i = function (e) {
                for (var t, i, a = "", n = 0, o = 0; n < e.length;)
                    (t = e.charCodeAt(n)) < 128 ? (a += String.fromCharCode(t),
                        n++) : 191 < t && t < 224 ? (o = e.charCodeAt(n + 1),
                            a += String.fromCharCode((31 & t) << 6 | 63 & o),
                            n += 2) : (o = e.charCodeAt(n + 1),
                                i = e.charCodeAt(n + 2),
                                a += String.fromCharCode((15 & t) << 12 | (63 & o) << 6 | 63 & i),
                                n += 3);
                return a
            }
    }
    function o(a) {
        return (new w).decode(a);
    }

    const props = items.map(async item => {
        item.remoteUrl = await fetch(item.remoteUrl)
            .then(resp => resp.text())
            .then(data => {
                if (!data) return
                const result = o(data)
                return result.substring(0, result.length - result.split('base64,')[1].length % 4)
            })
        return item
    })
    return Promise.all(props)
}

export const loadTopics = (url, params) => {
    return new Promise((resolve, reject) => {
        // 使用 URLSearchParams 对象构建查询字符串
        const queryString = new URLSearchParams(params).toString();
        fetch(url + '?' + queryString, { mode: 'cors' })
            .then(response => response.json())
            .then(data => {
                // 在这里处理返回的数据
                if (!data.success) {
                    console.log(data)
                    reject(data)
                    return
                }
                data.isEncrypted && (data.data = JSON.parse(base64ToUtf8(atob(atob(data.data)))))
                // console.log(data.data);

                resolve({ topics: data.data })
            })
            .catch(error => {
                // 处理错误
                console.error(error);
                reject(error)
            });
    })
}

export const loadFollow = (url : string, token : string, uid : string) => {
    return new Promise((resolve, reject) => {
        // 定义自定义的请求头信息
        const myHeaders = new Headers();
        myHeaders.append('X-User-Id', uid);
        myHeaders.append('X-User-Token', token);
        get(url, null, myHeaders).then(async (data: any)=> {
            resolve({follow: data})
        }).catch(err=>{
            reject(err)
        })
    })
}


export const get = (url: string, params: any=null, headers={}) => {
    return new Promise((resolve, reject) => {
        // 使用 URLSearchParams 对象构建查询字符串
        if (params) {
            url += '?' + new URLSearchParams(params).toString()
        }
        fetch(url, { mode: 'cors', headers})
            .then(response => response.json())
            .then(data => {
                // 在这里处理返回的数据
                if (!data.success) {
                    console.log(data)
                    reject(data.message)
                    return
                }
                data.isEncrypted && (data.data = JSON.parse(base64ToUtf8(atob(atob(data.data)))))
                resolve(data.data)
            })
            .catch(error => {
                // 处理错误
                console.error(error);
                reject(error)
            });
    })
}

export const openUrlWithNewTab = async (url : string) => {
    console.log(url)
    const resp = await sendMessage({ action: 'openTabWithUrl', url: url });
    console.log(resp)
}